package com.gdziarmaga.webshop.web.managedBeans.client;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.event.ActionEvent;

import org.springframework.beans.factory.annotation.Autowired;

import com.gdziarmaga.webshop.client.model.Client;
import com.gdziarmaga.webshop.client.services.ClientManager;
import com.gdziarmaga.webshop.utils.springcontext.AppContext;
import com.gdziarmaga.webshop.web.menus.AdminPanelBean;
import com.gdziarmaga.webshop.web.utils.FacesUtils;

@ManagedBean(name = "manageClientBean")
@RequestScoped
public class ManageClientBean {

	@Autowired
	private ClientManager clientManager;

	@PostConstruct
	public void init() {
		clientManager = (ClientManager) AppContext.getApplicationContext()
				.getBean("clientManager");
	}

	private Client client;

	public Client getClient() {
		if (client == null) {

			if (!editClient()) {
				client = new Client();
			}
		}
		return client;
	}

	public void setClient(Client client) {
		this.client = client;
	}

	public boolean editClient() {
		AdminPanelBean bean = ((AdminPanelBean) FacesUtils.getRequest()
				.getSession().getAttribute("adminPanelBean"));
		if (!bean.getSelectionItems().isEmpty()) {
			if (bean.getSelectionItems().get(0) instanceof Client) {
				Long id = ((Client) bean.getSelectionItems().get(0))
						.getClient_id();
				setClient(clientManager.getClientById(id));
				return true;
			}
		}
		return false;
	}

	public void createClient(ActionEvent event) {
		client.setFlag(1);
		clientManager.saveClient(client);
		client = null;
	}

	public void removeClient() {
		AdminPanelBean bean = ((AdminPanelBean) FacesUtils.getRequest()
				.getSession().getAttribute("adminPanelBean"));
		Long id = ((Client) bean.getSelectionItems().get(0)).getClient_id();
		if (id != null) {
			FacesUtils.flashScope().put("selectedObjectId", id);
			clientManager.removeClientById(id);
		}
	}
}
